package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    //自定义一个线程池，防止缓存击穿中，逻辑过期处理频繁的创建销毁线程
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    @Override
    @Transactional
    public Result update(Shop shop) {
        Long id = shop.getId();
        if (id == null){
            return Result.fail("店铺id为空，无法更新。");
        }
        //1、更新数据库
        updateById(shop);

        //2、删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);
        return Result.ok();
    }

    @Override
    public Result queryById(Long id) {

        //解决缓存穿透问题
//        Shop shop = queryWithRedisThrough(id);
        //用封装的redis工具类查
//        Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);


        //利用互斥锁解决缓存击穿问题
//        Shop shop = redisJiChuanLock(id);
        //用封装的redis工具类查
        Shop shop = cacheClient.queryWithMutex(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        //利用逻辑过期解决缓存击穿问题
//        Shop shop = queryWithLogicalExpire(id);
        //用封装的redis工具类查
//        Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, this::getById, CACHE_SHOP_TTL, TimeUnit.MINUTES);

        if (shop == null){
            return Result.fail("该商户信息不存在");
        }

        return Result.ok(shop);
    }

    /**
     * 解决缓存穿透问题
     */
    private Shop queryWithRedisThrough(Long id){
        //1、根据id从redis中查询商铺数据
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);

        //2、判断是否从redis中查到数据
        if(StrUtil.isNotBlank(shopJson)){
            //查到了,将json格式数据转化为bean
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }else if (shopJson != null){
            //如果redis命中的是“ ”
            return null;
        }

        Shop shop = getById(id);

        //5、判断数据库中是否查得到
        if(shop == null){
            //没查到,为了防止缓存穿透，将空值写入redis,过期时间2分钟
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }

        //6、查到了，写入redis,31~35分钟后过期,防止缓存雪崩设置存活时间不同
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL + (int)(Math.random()*(5-1)+1), TimeUnit.MINUTES);
        return shop;
    }

    /**
     * 利用setnx来自定义一个互斥锁，来解决缓存击穿问题
     * tryLock用来获取锁
     * unlock用来释放锁
     */
    private boolean tryLock(String key){
        //锁10秒后没线程释放，就自动释放，防止死锁
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }

    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }

    /**
     * 利用互斥锁解决缓存击穿问题
     */
    private Shop redisJiChuanLock(Long id){
        //1、根据id从redis中查询商铺数据
        String shopJson = stringRedisTemplate.opsForValue().get(CACHE_SHOP_KEY + id);

        //2、判断是否从redis中查到数据
        if(StrUtil.isNotBlank(shopJson)){
            //查到了,将json格式数据转化为bean
            Shop shop = JSONUtil.toBean(shopJson, Shop.class);
            return shop;
        }else if (shopJson != null){
            //如果redis命中的是“ ”
            return null;
        }

        //3、实现缓存重建
        //3.1、获取互斥锁
        String lockKey = LOCK_SHOP_KEY + id;
        Shop shop = null;
        try {
            boolean isLock = tryLock(lockKey);

            //3.2、判断是否获取成功
            if (!isLock){
                //3.3、失败，则休眠重试
                Thread.sleep(50);
            }

            //3.4、成功，则根据id查数据库
            //4、redis中不存在，则根据id去数据库里查
            shop = getById(id);

            //5、判断数据库中是否查得到
            if(shop == null){
                //没查到,为了防止缓存穿透，将空值写入redis,过期时间2分钟
                stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }

            //6、查到了，写入redis,31~35分钟后过期,防止缓存雪崩设置存活时间不同
            stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(shop),CACHE_SHOP_TTL + (int)(Math.random()*(5-1)+1), TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }finally {
            //7、释放互斥锁
            unlock(lockKey);
        }
        return shop;
    }

    /**
     * 利用逻辑过期解决缓存击穿问题
     */
    private Shop queryWithLogicalExpire(Long id){

        String key = LOCK_SHOP_KEY + id;
        //1、从redis中获取商铺缓存
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //2、判断是否存在
        if (StrUtil.isBlank(shopJson)){
            //不存在直接返回null
            return null;
        }

        //3、命中,把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        Shop shop =JSONUtil.toBean((JSONObject) redisData.getData(),Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //4、判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //4.1、未过期直接返回店铺信息
            return shop;
        }

        //5、已经过期，缓存重建
        //5.1、获取互斥锁
        boolean isLock = tryLock(key);
        //5.2、判断是否取锁成功
        if (isLock){
            //5.3、成功，开启独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //缓存重建
                    this.saveShopToRedis(id,20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unlock(key);
                }
            });
        }
        //6、返回商铺信息
        return shop;
    }

    /**
     * 存储店铺逻辑过期时间,预热
     */
    public void saveShopToRedis(Long id,Long expireSeconds){
        //1.查询店铺数据
        Shop shop = getById(id);
        //2、封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //3、写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id,JSONUtil.toJsonStr(redisData));
    }
}
